package com.example.userservice.controller;

import com.example.userservice.client.CourseClient;
import com.example.userservice.client.EnrollClient;
import com.example.userservice.client.HomeworkClient;
import com.example.userservice.config.FileUploadConfig;
import com.example.userservice.entity.user_account;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping
public class TeacherCourseController {

    @Autowired
    private CourseClient courseClient;
    
    @Autowired
    private EnrollClient enrollClient;
    
    @Autowired
    private HomeworkClient homeworkClient;
    
    @Autowired
    private FileUploadConfig fileUploadConfig;
    
    @Value("${file.upload.path}")
    private String uploadPath;


    @PostMapping("/teacher/course/add")
    @ResponseBody
    public String addCourse(String title, String description, String coverUrl, String category, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        Map<String, Object> body = new HashMap<>();
        body.put("title", title);
        body.put("description", description);
//        body.put("coverUrl", coverUrl);
//        body.put("category", category);
        body.put("createdBy", user.getId());
        return courseClient.createCourse(body);
    }

    @GetMapping("/teacher/course/list")
    @ResponseBody
    public java.util.List<java.util.Map<String, Object>> listMyCourses(HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return java.util.Collections.emptyList();
        }
        return courseClient.listCourses((int)user.getId());
    }

    @GetMapping("/teacher/course/chapters")
    @ResponseBody
    public java.util.List<java.util.Map<String, Object>> listCourseChapters(int courseId) {
        return courseClient.listChapters(courseId);
    }

    @PostMapping("/teacher/course/chapter/add")
    @ResponseBody
    public String addChapter(int courseId, String title) {
        Map<String, Object> body = new HashMap<>();
        body.put("title", title);
        body.put("courseId", courseId);
        String rs =courseClient.createChapter(body);
        return rs;
    }
    
    @PostMapping("/teacher/course/chapter/delete")
    @ResponseBody
    public String deleteChapter(@RequestParam int chapterId) {
        return courseClient.deleteChapter(chapterId);
    }
    
    @GetMapping("/teacher/course/{courseId}/students")
    @ResponseBody
    public java.util.List<java.util.Map<String, Object>> getCourseStudents(@PathVariable int courseId) {
        return enrollClient.getCourseEnrollments(courseId);
    }
    
    @PostMapping("/teacher/enrollment/approve")
    @ResponseBody
    public String approveEnrollment(@RequestBody Map<String, Object> requestBody, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        requestBody.put("decidedBy", user.getId());
        return enrollClient.approveEnrollment(requestBody);
    }
    
    @PostMapping("/teacher/enrollment/reject")
    @ResponseBody
    public String rejectEnrollment(@RequestBody Map<String, Object> requestBody, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        requestBody.put("decidedBy", user.getId());
        return enrollClient.rejectEnrollment(requestBody);
    }

    // 课件上传
    @PostMapping("/teacher/course/material/upload")
    @ResponseBody
    public String uploadMaterial(@RequestParam("file") MultipartFile file,
                                @RequestParam("name") String name,
                                @RequestParam("courseId") int courseId,
                                @RequestParam("chapterId") int chapterId,
                                HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            if (file.isEmpty()) {
                return "文件不能为空";
            }

            // 创建上传目录 - 使用配置的路径
            String coursewareDir = uploadPath + "courseware" + File.separator;
            File dir = new File(coursewareDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    return "创建上传目录失败";
                }
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = UUID.randomUUID().toString() + extension;
            String filePath = coursewareDir + uniqueFilename;

            // 保存文件
            file.transferTo(new File(filePath));

            // 调用course-service保存数据库记录
            // 存储相对路径，便于跨平台兼容
            String relativePath = "courseware" + File.separator + uniqueFilename;
            Map<String, Object> materialData = new HashMap<>();
            materialData.put("courseId", courseId);
            materialData.put("chapterId", chapterId);
            materialData.put("type", 1); // 1表示课件
            materialData.put("name", name);
            materialData.put("url", relativePath);
            materialData.put("sizeBytes", (int) file.getSize());
            materialData.put("contentType", file.getContentType());
            materialData.put("uploaderId", (int)user.getId());
            materialData.put("createdAt", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            return courseClient.saveMaterial(materialData);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败: " + e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败: " + e.getMessage();
        }
    }

    // 获取章节课件列表
    @GetMapping("/teacher/course/{courseId}/chapter/{chapterId}/materials")
    @ResponseBody
    public java.util.List<java.util.Map<String, Object>> getChapterMaterials(@PathVariable int courseId, @PathVariable int chapterId) {
        return courseClient.getChapterMaterials(courseId, chapterId);
    }

    // 下载课件
    @GetMapping("/teacher/course/material/{materialId}/download")
    public ResponseEntity<Resource> downloadMaterial(@PathVariable int materialId) {
        try {
            // 先获取课件信息
            Map<String, Object> materialInfo = courseClient.getMaterialInfo(materialId);
            if (materialInfo == null) {
                return ResponseEntity.notFound().build();
            }

            String relativePath = (String) materialInfo.get("url");
            // 将相对路径转换为绝对路径
            String filePath = uploadPath + relativePath.replace("/", File.separator);
            Path path = Paths.get(filePath);
            
            if (!Files.exists(path)) {
                return ResponseEntity.notFound().build();
            }

            byte[] data = Files.readAllBytes(path);
            String contentType = (String) materialInfo.get("contentType");
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            ByteArrayResource resource = new ByteArrayResource(data);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + materialInfo.get("name") + "\"")
                    .body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }

    // 删除课件
    @DeleteMapping("/teacher/course/material/{materialId}/delete")
    @ResponseBody
    public String deleteMaterial(@PathVariable int materialId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            // 先获取课件信息
            Map<String, Object> materialInfo = courseClient.getMaterialInfo(materialId);
            if (materialInfo == null) {
                return "课件不存在";
            }

            // 删除文件
            String relativePath = (String) materialInfo.get("url");
            // 将相对路径转换为绝对路径
            String filePath = uploadPath + relativePath.replace("/", File.separator);
            File file = new File(filePath);
            if (file.exists()) {
                boolean deleted = file.delete();
                if (!deleted) {
                    return "文件删除失败";
                }
            }

            // 删除数据库记录
            return courseClient.deleteMaterial(materialId);
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败: " + e.getMessage();
        }
    }

    // ==================== 作业管理相关方法 ====================
    
    // 创建作业
    @PostMapping("/teacher/course/homework/create")
    @ResponseBody
    public String createHomework(@RequestParam int courseId, 
                                @RequestParam String title,
                                @RequestParam String content,
                                @RequestParam String ddlTime,
                                @RequestParam double totalScore,
                                HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("courseId", courseId);
            requestBody.put("title", title);
            requestBody.put("content", content);
            requestBody.put("ddlTime", ddlTime);
            requestBody.put("totalScore", totalScore);
            requestBody.put("createdBy", user.getId());
            
            return homeworkClient.createHomework(requestBody);
        } catch (Exception e) {
            e.printStackTrace();
            return "创建作业失败: " + e.getMessage();
        }
    }
    
    // 获取课程的作业列表
    @GetMapping("/teacher/course/{courseId}/homeworks")
    @ResponseBody
    public Object getCourseHomeworks(@PathVariable int courseId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return homeworkClient.getCourseHomeworks(courseId);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取作业列表失败: " + e.getMessage();
        }
    }
    
    // 获取作业详情
    @GetMapping("/teacher/course/homework/{homeworkId}")
    @ResponseBody
    public Object getHomeworkDetail(@PathVariable int homeworkId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return homeworkClient.getHomeworkDetail(homeworkId);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取作业详情失败: " + e.getMessage();
        }
    }
    
    // 更新作业
    @PutMapping("/teacher/course/homework/update")
    @ResponseBody
    public String updateHomework(@RequestParam int homeworkId,
                                @RequestParam String title,
                                @RequestParam String content,
                                @RequestParam String ddlTime,
                                @RequestParam double totalScore,
                                HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("homeworkId", homeworkId);
            requestBody.put("title", title);
            requestBody.put("content", content);
            requestBody.put("ddlTime", ddlTime);
            requestBody.put("totalScore", totalScore);
            
            return homeworkClient.updateHomework(requestBody);
        } catch (Exception e) {
            e.printStackTrace();
            return "更新作业失败: " + e.getMessage();
        }
    }
    
    // 删除作业
    @DeleteMapping("/teacher/course/homework/{homeworkId}")
    @ResponseBody
    public String deleteHomework(@PathVariable int homeworkId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return homeworkClient.deleteHomework(homeworkId);
        } catch (Exception e) {
            e.printStackTrace();
            return "删除作业失败: " + e.getMessage();
        }
    }
    
    // ==================== 作业提交管理相关方法 ====================
    
    // 获取作业的提交记录
    @GetMapping("/teacher/course/homework/{homeworkId}/submissions")
    @ResponseBody
    public Object getHomeworkSubmissions(@PathVariable int homeworkId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return homeworkClient.getHomeworkSubmissions(homeworkId);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取提交记录失败: " + e.getMessage();
        }
    }
    
    // 批改作业
    @PutMapping("/teacher/course/homework/grade")
    @ResponseBody
    public String gradeHomework(@RequestParam int submissionId,
                               @RequestParam String score,
                               @RequestParam String feedback,
                               HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("submissionId", submissionId);
            requestBody.put("score", score);
            requestBody.put("feedback", feedback);
            requestBody.put("gradedBy", user.getId());
            
            return homeworkClient.gradeHomework(requestBody);
        } catch (Exception e) {
            e.printStackTrace();
            return "批改作业失败: " + e.getMessage();
        }
    }

}


